<template>
  <a-row>
    <div class="total-table-container">
      <a-row style="margin-bottom: 8px;">
        <a-col :span="2" style="float: right;">
          <ExportFile
            :fetch="getDownloadData"
            :fields="jsonFields"
            name="downloadFile.xls"
          >
            <a-button
              class="editable-add-btn"
              type="primary"
              :loading="iconLoading"
              >导出</a-button
            >
          </ExportFile>
        </a-col>
      </a-row>
      <a-row>
        <a-table
          :columns="tableColumns"
          :data-source="tableDataLists"
          :scroll="{ x: 1200 }"
          :rowKey="
            (record, index) => {
              return index;
            }
          "
          :customRow="clickSingleRow"
          :pagination="paginationOpt"
          :loading="isLoading"
          bordered
          @change="handleTableChange"
        >
        </a-table>
      </a-row>
    </div>

    <a-modal
      v-if="isDialogOpen"
      v-model="isDialogOpen"
      dialogClass="dialog"
      centered
      title="记录详情"
      class="dispatch-modal"
      width="80%"
      :footer="null"
      @cancel="assignModalCloseBtn"
      :bodyStyle="{ padding: '0 0 20px 0' }"
    >
      <a-menu v-model="currMenu" mode="horizontal">
        <a-menu-item key="1">基本信息</a-menu-item>
        <a-menu-item key="2">版本检测</a-menu-item>
        <a-menu-item key="3">电机检测</a-menu-item>
      </a-menu>
      <div v-show="currMenu == '1'" class="dialog-content">
        <!-- {{productInfo}} -->
        <a-form
          :footer="false"
          :formOptions="formOptions"
          :col="3"
          :defaultFormData="productInfo"
          @submit="updateInfo"
        >
          <template slot="footer">
            <a-form v-for="(item,index) in productInfo.servos" :key="index"
            :footer="false"
            ></a-form>
            <div class="dialog-footer">
              <a-button class="footer-btn" type="primary" html-type="submit">
              修改记录
            </a-button>
            <a-button class="footer-btn" type="danger" @click="deleteProduct">
              删除记录
            </a-button>
            </div>
          </template>
        </a-form>
      </div>
      <div v-show="currMenu == '2'" class="dialog-content">
        <!-- {{ versionList }} -->
        <a-table
          :columns="versionColumns"
          :row-key="
            (record, index) => {
              return index;
            }
          "
          :data-source="versionList"
          :pagination="false"
        >
        <template slot="isEqueal" slot-scope="text">
            <a-icon v-if="text== 0" type="check" style="color:green;"/>
          <a-icon v-else type="close" style="color:red;" />
        </template>
        </a-table>
      </div>
      <div v-show="currMenu == '3'" class="dialog-content">
        <a-table
          :columns="motorColumns"
          :row-key="
            (record, index) => {
              return index;
            }
          "
          :data-source="motorList"
          :pagination="false"
        ></a-table>
      </div>
    </a-modal>
  </a-row>
</template>

<script>
import api from "@/server/ncCheckConfig";
import { columns, formOptions, versionColumns,motorColumns } from "./tableConfig";
import ExportFile from "vue-json-excel";
import aForm from "./form";

function buildJsonFields(lists) {
  let jsonFields = {};
  lists.forEach((item, index) => {
      jsonFields[item.title] = item.dataIndex;
  });
  return jsonFields;
}

export default {
  name: "HistoryOrderTable",
  props: {
    searchData: Object
  },
  components: {
    ExportFile,
    aForm
  },
  data() {
    return {
      userName: "",
      role: "",
      compId: "",
      tableColumns: columns,
      versionColumns: versionColumns,
      motorColumns: motorColumns,
      tableDataLists: [],
      isLoading: false,
      isDialogOpen: false,
      currMenu: [],
      formOptions: formOptions,
      productInfo: {},
      rowData: {},
      versionList: [],
      motorList: [],
      jsonFields: buildJsonFields([...columns, {
      title: "登录用户",
      dataIndex: "loginName",
      width: "100px",
      ellipsis: false,
      ellipsis: true
    }]),

      paginationOpt: {
        current: 1,
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showTotal: total => `共 ${total} 条`, // 显示总数
        // 点击分页时事件
        onChange: (current, size) => {
          let _this = this;
          this.getAllRepair({ pageNum: current }, "tableDataLists");
        }
      },
      iconLoading: false
    };
  },
  computed: {},
  watch: {
    searchData: function(newVal, oldVal) {
      let _this = this;
      _this.getData({ pageNum: 1 });
    },
    currMenu: {
      immediate: true,
      deep: true,
      handler: function(val) {
        switch (val[0]) {
          case "1":
            this.selProductByProductId(this.rowData.productId);
            break;
          case "2":
            this.selNcverByProductId(this.rowData.productId);
            break;
          case "3":
            this.selMotorByProductId(this.rowData.productId)
            break;

          default:
            break;
        }
      }
    }
  },
  created() {},
  mounted() {
    this.getData({ pageNum: 1 });
  },
  methods: {
    getData(parames) {
      this.getAllRepair(parames, "tableDataLists");
    },
    handleTableChange(pagination) {
      this.paginationOpt.current = pagination.current;
    },
    // Table 获取数据
    async getAllRepair(parames, key) {
      let _this = this;
      let { pageNum } = parames;
      _this.isLoading = true;
      // let {beginTime,endTime,...rest} = _this.searchData
      const res = await api.selProductBySelString({
        username:  localStorage.getItem('username') ?  localStorage.getItem('username') : '',
        pageNum,
        pageSize: _this.paginationOpt.defaultPageSize,
        // beginTime: (beginTime.length && beginTime) || `${moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')}%2000:00:00`,
        // endTime: (endTime.length && endTime) || `${moment(new Date()).format('YYYY-MM-DD')}%2023:59:59`,
        ..._this.searchData
      });

      _this.isLoading = false;
      if (res.msgCode !== 0) {
        this.paginationOpt.total = 0
        this[key] = []
        return;
      }
      this.paginationOpt.current = pageNum || 1
      this.paginationOpt.total = res.data.total || 0;

      let newObj = res.data.rows || [];
      this[key] = newObj;
    },

    // 点击每一行的跳转;
    clickSingleRow(record, index) {
      return {
        on: {
          click: () => {
            this.rowData = record;
            this.currMenu = ["1"];
            // this.selProductByProductId(record.productId)
          }
        }
      };
    },
    //根据id查信息
    selProductByProductId(productId) {
      let data = {
        productId
      };
      api.selProductByProductId(data).then(res => {
        if (res.msgCode != 0) {
          return;
        }
        this.productInfo = res.data;
        this.isDialogOpen = true;
      });
    },
    //查询版本检测信息
    selNcverByProductId(productId) {
      let data = {
        productId
      };
      api.selNcverByProductId(data).then(res => {
        if (res.msgCode != 0) {
          return;
        }
        this.versionList = res.data;
      });
    },
    //查询电机检测列表
    selMotorByProductId(productId){
      let data = {
        productId
      };
      api.selMotorByProductId(data).then(res => {
        if (res.msgCode != 0) {
          return;
        }
        this.motorList = res.data.motor;
      });
    },
    //导出
    getProductsByParam(){
      api.getProductsByParam(this.searchData)
    },
    updateInfo(values) {
      let data = { ...values, productID: this.rowData.productId };
      api.updateProduct(data).then(res => {
        if (res.msgCode != 0) {
          console.log("修改失败");
          return;
        }
        this.$message.success("修改成功");
      });
    },
    deleteProduct() {
      let that = this;
      this.$Modal.confirm({
        title: "删除",
        content: "确认删除？",
        onOk() {
          let data = {
            productId: that.rowData.productId
          };
          api.deleteProduct(data).then(res => {
            if (res.msgCode != 0) {
              that.$message.error("删除失败");
              return;
            }
            that.$message.success("删除成功");
            that.isDialogOpen = false;
            that.getData({ pageNum: that.paginationOpt.current });
          });
        }
      });
    },

    // 指派弹框ok按钮
    assignModalOKBtn() {},
    // 指派弹框close按钮
    assignModalCloseBtn(item) {},

    // 获取需要导出的数据
    async getDownloadData() {
      let _this = this;
      if (_this.iconLoading == true) {
        return false;
      }
      let total = _this.paginationOpt.total;
      let pageSize = 300;
      let length = Math.ceil(total / pageSize);
      let newLists = [];
      _this.iconLoading = true;
      for (let i = 1; i <= length; i++) {
        let lists = await this.buildDownloadLists({
          pageNum: i,
          pageSize: pageSize
        });
        newLists.push(lists);
      }
      _this.iconLoading = false;
      return [].concat(...newLists);
    },

    async buildDownloadLists(parames) {
      let _this = this;
      let { pageNum, pageSize } = parames;
      const res = await api.selProductBySelString({
        username:  localStorage.getItem('username') ?  localStorage.getItem('username') : '',
        pageNum,
        pageSize,
        ..._this.searchData
      });

      if (res.msgCode !== 0) {
        return;
      }
      let list = res.data.rows
      // list.forEach(e=> {
      //   if(e.uploadTime && typeof e.uploadTime == "number") {
      //     e.uploadTime = moment((e.uploadTime-8*60*60)*1000).format(`YYYY-MM-DD HH:mm:ss`)
      //   }
      // })
      return list;
    },
  }
};
</script>

<style lang="css" scoped>
@import "./style.css";
.itemWrap {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
}

.itemWrap > .label {
  min-width: 90px;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #373737;
  text-align: right;
}

.itemWrap > .separator {
  padding: 0px 4px;
}

.itemWrap > .content {
  width: 100%;
  padding: 0px 1px;
}
.dialog-content {
  padding: 16px;
  height: 70vh;
  overflow: auto;
}
.dialog-footer {
  /* display: flex; */
  width: 100%;
  text-align: center;
}
.dialog-footer .footer-btn {
  margin-right: 16px;
}
</style>
